package edu.pku.sei.transformation.editor.parser.texttemplate.equivalence;

import java.util.HashSet;
import java.util.Set;

import edu.pku.sei.transformation.editor.parser.texttemplate.element.ElementEdge;

public class EquivalenceLink extends EquivalenceElement<ElementEdge> {
	public EquivalenceNode source = null;
	public EquivalenceNode target = null;
	public Set<EquivalenceLink> rightside = new HashSet<EquivalenceLink>();
	public Set<EquivalenceLink> leftside = new HashSet<EquivalenceLink>();
	public int weight = 0;
	
	@Override
	public boolean merge(EquivalenceElement otherLink) {
		if (otherLink instanceof EquivalenceLink) {
//			((EquivalenceLink) otherLink).source.outgoings.remove(otherLink);
//			((EquivalenceLink) otherLink).source.outgoings.add(this);
//			((EquivalenceLink) otherLink).target.incomings.remove(otherLink);
//			((EquivalenceLink) otherLink).target.incomings.add(this);
			
			for (EquivalenceLink leftLink : ((EquivalenceLink) otherLink).leftside) {
				leftLink.rightside.remove(otherLink);
				leftLink.addRightLink(this);
			}
			
			for (EquivalenceLink rightLink : ((EquivalenceLink) otherLink).rightside) {
				rightLink.leftside.remove(otherLink);
				this.addRightLink(rightLink);
			}
			return super.merge(otherLink);
		} else {
			return false;
		}
	}
	
	public boolean addRightLink(EquivalenceLink rightLink) {
		if (rightLink != null) {
			this.rightside.add(rightLink);
			rightLink.leftside.add(this);
			return true;
		} else {
			return false;
		}
	}
	
	@Override
	public String toString() {
		String s = "<link ";
		s += "id="+this.hashCode()+" w="+weight+">\n";
		s += "<target>\n" + target.toString() + "</target>\n";
		for (EquivalenceLink link : rightside) {
			s += "<right id=" + link.hashCode() + "/>\n";
		}
		s += "</link>\n";
		return s;
	}

}
